package com.cs.controller.orders;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cs.controller.utils.R;
import com.cs.pojo.*;
import com.cs.service.IUserService;
import com.cs.service.IngredientInfo.IIngredientInfoService;
import com.cs.service.SizeInfo.ISizeInfoService;
import com.cs.service.goods.IgoodsService;
import com.cs.service.orders.IOrderIngredientDetailService;
import com.cs.service.orders.IOrdersDetailService;
import com.cs.service.orders.IOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/orders")
public class OrderController_R {
    @Autowired
    private IOrdersService iOrdersService;
    @Autowired
    private IgoodsService igoodsService;
    @Autowired
    private IOrdersDetailService iOrdersDetailService;
    @Autowired
    private IOrderIngredientDetailService iOrderIngredientDetailService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private ISizeInfoService iSizeInfoService;
    @Autowired
    private IIngredientInfoService iIngredientInfoService;
    @GetMapping()
    public R getAll(){
        System.out.println("getAll");
        List<Order> orderList = iOrdersService.list();
        orderFormat(orderList);
        return new R("200",orderList);
    }

    /**
     * 添加订单
     * @param order
     * @return
     */
    @PostMapping()
    @Transactional
    public R save(@RequestBody Order order) throws ParseException {
        java.util.Date date = new Date();//获得当前时间
        Timestamp t = new Timestamp(date.getTime());//将时间转换成Timestamp类型，这样便可以存入到Mysql数据库中
        order.setCreateTime(t);

        System.out.println(order+"////////////////");

        OrderDetail orderDetail=new OrderDetail();
        OrderIngredientDetail orderIngredientDetail = new OrderIngredientDetail();
        String orderId="";
        List<Order> list;
        while (true)
        {
            for (int i = 1; i <= 7; i++) {
                Random random = new Random();
                int result = random.nextInt(10);
                orderId += result;
            }
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderId);
            list = iOrdersService.list(queryWrapper);
            if (list.isEmpty()) {
               break;
            }
        }
        //订单表 订单号
        order.setOrderId(orderId);

        //订单-小料表
        orderIngredientDetail.setOrderId(orderId);
        orderDetail.setOrderId(orderId);

        LambdaQueryWrapper<User> ulq = new LambdaQueryWrapper<>();
        ulq.eq(User::getPhone,order.getPhone());
        User user = iUserService.getOne(ulq);
        System.out.println(user.toString()+"******************");
        Double discount=1.00;
        Double totalPrice = 0.0;
        Double savePrice=0.0;
        switch (user.getVip()){
            case 1: discount=1.00; break;
            case 2: discount=0.98; break;
            case 3: discount=0.93; break;
            case 4: discount=0.88; break;
            case 5: discount=0.82; break;
            case 6: discount=0.77; break;
            case 7: discount=0.70; break;
            case 8: discount=0.65; break;
            case 9: discount=0.60; break;
            default:
                discount=1.00;break;
        }
        order.setDiscount(discount);
        System.out.println(user+"+++++++++++++++");
        for (Goods i : order.getGoods()) {
            orderDetail.setGoodId(i.getId());
            Goods goodById = igoodsService.getById(i.getId());
            totalPrice+=goodById.getPrice();
            orderDetail.setGoodNum(i.getGoodNum());
            if(i.getSize()==null){
                orderDetail.setSize("中杯");
            }else {
                orderDetail.setSize(i.getSize());
            }
            LambdaQueryWrapper<SizeInfo> iSizeInfoLqw = new LambdaQueryWrapper<>();
            iSizeInfoLqw.eq(SizeInfo::getSize,orderDetail.getSize());
            SizeInfo sizeInfo = iSizeInfoService.getOne(iSizeInfoLqw);
            totalPrice+=sizeInfo.getPrice();
            if(i.getTemperature()!=null){
                orderDetail.setTemperature(i.getTemperature());
            }
            if(i.getSweetness()!=null){
                orderDetail.setSweetness(i.getSweetness());
            }
            iOrdersDetailService.save(orderDetail);
            orderIngredientDetail.setGoodId(i.getId());
            orderIngredientDetail.setGoodNum(i.getGoodNum());

            if(i.getIngredientList()!=null){

                for (String ingredient:i.getIngredientList()){
                    orderIngredientDetail.setIngredient(ingredient);
                    LambdaQueryWrapper<IngredientInfo> IngredientLQW = new LambdaQueryWrapper<>();
                    IngredientLQW.eq(IngredientInfo::getIngredient,ingredient);
                    IngredientInfo ingredientOne = iIngredientInfoService.getOne(IngredientLQW);
                    totalPrice+=ingredientOne.getPrice();
                    iOrderIngredientDetailService.save(orderIngredientDetail);
                }

            }

        }
        order.setTotalPrice(totalPrice);
        savePrice=totalPrice-(totalPrice*discount);
        totalPrice=totalPrice*discount;
        order.setPayMoney(totalPrice);
        order.setSaveMoney(savePrice);

        iOrdersService.save(order);
        return new R("200", "添加成功");

    }
    @PutMapping
    public R update(@RequestBody Order order){
        return new R("200",iOrdersService.updateById(order),"修改成功");
    }
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id){

        return new R("200",iOrdersService.removeById(id),"删除成功");
    }
    @GetMapping("/{orderId}")

    public R selectByOrderId(@PathVariable String orderId){
        ArrayList<Goods> goodsList = new ArrayList<>();
        LambdaQueryWrapper<Order> lambdaQueryWrapper=new LambdaQueryWrapper<Order>();
        lambdaQueryWrapper.eq(Order::getOrderId,orderId);
        Order orderResult = iOrdersService.getOne(lambdaQueryWrapper);
        LambdaQueryWrapper<OrderDetail> odLQW = new LambdaQueryWrapper<>();
        odLQW.eq(OrderDetail::getOrderId,orderResult.getOrderId());
        List<OrderDetail> orderDetailList = iOrdersDetailService.list(odLQW);
        for (OrderDetail detail : orderDetailList) {
            Goods good = igoodsService.getById(detail.getGoodId());
            System.out.println(good.toString()+"++++++++++++++++++");
            good.setSweetness(detail.getSweetness());
            good.setTemperature(detail.getTemperature());
            good.setGoodNum(detail.getGoodNum());
            good.setSize(detail.getSize());
            LambdaQueryWrapper<OrderIngredientDetail> oidLQW = new LambdaQueryWrapper<>();
            oidLQW.eq(OrderIngredientDetail::getOrderId,detail.getOrderId())
                    .eq(OrderIngredientDetail::getGoodId,detail.getGoodId())
                    .eq(OrderIngredientDetail::getGoodNum,detail.getGoodNum());
            ArrayList<String> ingredientList = new ArrayList<>();
            List<OrderIngredientDetail> orderIngredientDetailList = iOrderIngredientDetailService.list(oidLQW);
            for (OrderIngredientDetail orderIngredientDetail : orderIngredientDetailList) {
                ingredientList.add(orderIngredientDetail.getIngredient());
            }
            good.setIngredientList(ingredientList);
            goodsList.add(good);
        }
        orderResult.setGoods(goodsList);
        ArrayList<Order> resOrder = new ArrayList<>();
        resOrder.add(orderResult);
        return new R("200",resOrder);
    }

    /**
     * 分页获取全部订单
     * @param currentPage
     * @param size
     * @return
     */
    @GetMapping("/page/{currentPage}/{size}")
    public R getAllByPage(@PathVariable int currentPage,@PathVariable int size){
        IPage<Order> page = iOrdersService.getPage(currentPage, size);
        page.setRecords(orderFormat(page.getRecords()));
        return new R("200",page);
    }

    /**
     * 根据订单号查询
     * @param orderId
     * @return
     */


    /**
     * 根据手机号查询 分页
     * @param currentPage
     * @param size
     * @param phone
     * @return
     */
    @GetMapping("/pageByPhone/{currentPage}/{size}/{phone}")
    public R getByPhonePage(@PathVariable int currentPage,@PathVariable int size,@PathVariable String phone){
        IPage<Order> page = iOrdersService.getPageByPhone(currentPage,size,phone);
        page.setRecords(orderFormat(page.getRecords()));
        return new R("200",page);
    }

    /**
     * 格式化订单对象
     * @param ordersList
     * @return
     */
    public List<Order> orderFormat(List<Order> ordersList){
        for (Order order : ordersList) {
            ArrayList<Goods> goodsList = new ArrayList<>();
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId,order.getOrderId());
            List<OrderDetail> orderDetailList = iOrdersDetailService.list(lambdaQueryWrapper);
            for (OrderDetail orderDetail : orderDetailList) {
                Goods good = igoodsService.getById(orderDetail.getGoodId());
                ArrayList<String> ingredientList = new ArrayList<>();
                good.setSize(orderDetail.getSize());
                good.setTemperature(orderDetail.getTemperature());
                good.setSweetness(orderDetail.getSweetness());
                good.setGoodNum(orderDetail.getGoodNum());

                LambdaQueryWrapper<OrderIngredientDetail> LQIngredient = new LambdaQueryWrapper<>();
                LQIngredient.eq(OrderIngredientDetail::getOrderId,order.getOrderId())
                        .eq(OrderIngredientDetail::getGoodId,orderDetail.getGoodId())
                        .eq(OrderIngredientDetail::getGoodNum,orderDetail.getGoodNum());
                List<OrderIngredientDetail> ingredientDetailsList = iOrderIngredientDetailService.list(LQIngredient);
                for (OrderIngredientDetail OID : ingredientDetailsList) {
                    String s=OID.getIngredient();
                    ingredientList.add(s);
                }
                //计算价格
                good.setIngredientList(ingredientList);
                Double ingredientPrice=0.0;
                for (String s : ingredientList) {
                    LambdaQueryWrapper<IngredientInfo> price = new LambdaQueryWrapper<>();
                    price.eq(IngredientInfo::getIngredient,s);
                    IngredientInfo one = iIngredientInfoService.getOne(price);
                    ingredientPrice+= one.getPrice();
                }
                LambdaQueryWrapper<SizeInfo> sizePriceLmq = new LambdaQueryWrapper<>();
                sizePriceLmq.eq(SizeInfo::getSize,good.getSize());
                SizeInfo sizeInfo = iSizeInfoService.getOne(sizePriceLmq);

                Double resultPrice=good.getPrice()+sizeInfo.getPrice()+ingredientPrice;
                good.setPrice(resultPrice);
                goodsList.add(good);
            }
            order.setGoods(goodsList);
        }
        return ordersList;
    }
}
